<template>
  <div>
       <div  class="table-region">
            <div class="table-title" slot="table-title">
                <span class="table-title-span">公共区域开关</span>
            </div>
            <el-table :data="AnnounceList" style="width: 100%" v-loading="loading" border>
                <el-table-column label="标题" align="center" min-width="240" prop="title">
                </el-table-column>
                <el-table-column label="描述" align="center" min-width="660" prop="detail">
                </el-table-column>
                <el-table-column align="center" label="操作" min-width="140">
                    <template scope="scope">
                        <el-button type="text" class="btn-success" 
                        @click="closeChargeLimit(scope.row)">{{scope.row.btn}}
                        </el-button>
                        <el-button type="text" class="btn-success" v-if="scope.row.checkComment"
                        @click="checkComment(scope.row)">查看评论
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
       </div>
            <div class="table-region">
                <div class="table-title" slot="table-title">
                     <span class="table-title-span">开放时间设置</span>
                </div>
                <el-table :data="openTimeList" style="width: 100%" v-loading="loading" border>
                    <el-table-column label="时间段" align="center" 
                    type="index"
                    width="240">
                    </el-table-column>
                    <el-table-column label="开放时间" align="center" min-width="260">
                        <template scope="scope">
                           <span v-show="scope.row.beginTime">每天{{scope.row.beginTime|filterTime}}-{{scope.row.endTime|filterTime}}</span>
                           <span v-show="!scope.row.beginTime">--</span>
                        </template>
                    </el-table-column>
                    <el-table-column align="center" label="操作" min-width="100">
                        <template scope="scope">
                            <el-button type="text" class="btn-success" 
                            @click="updateTime(scope.row, scope.$index)">时间修改</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>       
            <div class="table-region">
                <div class="table-title" slot="table-title">
                     <span class="table-title-span">设备详情</span>
                </div>
                <el-table :data="deviceDetailList" style="width: 100%" v-loading="loading" border>
                    <el-table-column label="视角" align="center" prop="sAngleView" min-width="240">
                    </el-table-column>
                    <el-table-column label="摄像机配置" align="center"  min-width="660">
                     <template scope="scope">
                      <div>{{scope.row.hasClassTimeRule=='1'?'安装':'未安装'}}</div>
                    </template>
                    </el-table-column>
                    <el-table-column align="center" label="操作" min-width="100">
                         <template scope="scope">
                            <el-button type="text" class="btn-success" 
                            @click="deviceClose(scope.row)">{{scope.row.sOpen=='1'?'关闭':'开放'}}</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="pagination-container" style="text-align:right">
                    <el-pagination layout="total, sizes, prev, pager, next, jumper" :total="listQuery.total" :current-page.sync="listQuery.page" :page-sizes="config.pageSizes" :page-size="config.pageSize" @size-change="handleSizeChange" @current-change="handleCurrentChange">
                    </el-pagination>
                </div>
            </div>  
            <publicRegionDialog :addData="addData" v-if="addData.dialogAdd" @search="searchFetchData"></publicRegionDialog>         
  </div>
</template>
<script>

import { mapState, mapActions, mapGetters } from 'vuex';
import { pagePublicAreas,
 updatePublicAreaOpen, updatePublicAreaCharge, updateDeviceFlag} from 'api/deviceManagement';
import publicRegionDialog from './comp/publicRegionDialog';
import moment from 'moment';
export default {
    name: 'publicRegion',
    components: { publicRegionDialog},
    data() {
        return {
            addData: {// 查询 表单数据
                pId: '',
                fClassId: '', // 班级id（教学区域）或学校id（公共区域）
                indexRow: '', // 点击的第几个时间段
                updataTimePid: '',
                firstStart: '',
                firstEnd: '',
                secondStart: '',
                secondEnd: '',
                thirdStart: '',
                thirdEnd: '',
                dialogAdd: false,
                titleIndex: '',
                startTime: '',
                endTime: '',
                startRange: {
                    start: '',
                    end: ''
                },
                endRange: {
                    start: '', // 开始时间的v-model选中的时间
                    end: ''
                }
            },
            formInline: {
                schoolName: '', // 当前学校名字
                schoolId: '', // 当前学校id
                schoolNameList: []
               
            },
            pIdArr: [],
            listQuery: {// 分页
                page: 1,
                total: 0
            },
            loading: false,
            schoolLoading: false,
            // 公共区域
            AnnounceList: [],
            // 开放时间设置
            openTimeList: [
            ],
            // openTimeList: [],
            // 设备详情
            deviceDetailList: [],
            rules: {
                schoolId: [{ required: true, message: '请输入学校名称' }]
            },
            getSchoolInfor: null
        }
    },
    computed: {
        ...mapState({
            config: state => state.config.table,
            cacheUpdated: state => state.app.cacheUpdated// 局部刷新列表
        }),
        ...mapGetters([
            'uid',
            'schoolName',
            'schoolId'
        ])
    },
//    列表页添加watch：
    watch: {// 局部刷新列表
        cacheUpdated(val) {
            val && this.searchFetchData();
        }
    },

    created() {
         // 回填学校 查询班级
        this.formInline.schoolName=this.schoolName
        this.formInline.schoolId=this.schoolId;
        this.searchFetchData()
    },
    filters: {
        filterTime(val) {
            if (val) {
                return val.substring(0, 5)
            }
        }
    },
    methods: {
        ...mapActions(['ChangePageSize']),
     // 点击查看评论
        checkComment(row) {
            let id=this.schoolId;
            let status='2';
            this.$router.push({path: `checkComment/${id}/${status}`});
        },
        // 查询列表
        searchFetchData() {
            let page = this.listQuery.page;
            let rows = this.config.pageSize;
            let sSchoolId=this.formInline.schoolId;
            pagePublicAreas(page, rows, sSchoolId).then(res => {
                if (res.data.content.list) {
                    res.data.content.list.forEach((val, index) => {
                        this.pIdArr.push(val.pId)
                    });
                }
                this.deviceDetailList=res.data.content.list;// 所有信息
                this.listQuery.total = res.data.content.pagination.total;
                // 公共区域
                if (res.data.content.list!==null) {
                    this.addData.pId=res.data.content.list[0].pId
                    this.addData.updataTimePid=res.data.content.list[0].liveDeviceRule.pId;
                    this.AnnounceList=new Array(3);
                    this.AnnounceList=[
                        {
                            title: '公共区域',
                            detail: '',
                            btn: '',
                            checkComment: '1' // 查看评论按钮
                        },
                        {
                            title: '收费开关',
                            detail: '',
                            btn: ''
                        },
                        {
                            title: '是否限制教师的观看时间段',
                            detail: '',
                            btn: ''
                        } 
                    ];
                    this.AnnounceList[0].btn=res.data.content.list[0].open=='1'?'关闭':'开放';
                    this.AnnounceList[1].btn=res.data.content.list[0].sCharge=='1'?'免费':'收费';
                    this.AnnounceList[2].btn=res.data.content.list[0].sFlag=='1'?'不限制':'限制';
                    let openStatus=res.data.content.list[0].open=='1'?'开放':'关闭';
                    this.AnnounceList[0].detail=this.AnnounceList[0].btn=='关闭'?'当前为开放状态，公共区域已对家长开放':'当前为关闭状态，公共区域已对家长关闭';
                    this.AnnounceList[1].detail=this.AnnounceList[1].btn=='收费'?'当前为'+openStatus+'状态，移动端在公共区域开放状态下可免费观看':'当前为'+openStatus+'状态，移动端在公共区域开放状态下可收费观看';
                    this.AnnounceList[2].detail=this.AnnounceList[2].btn=='不限制'?'限制时，教师与家长的观看时间段相同，不限制时教师为全天候都可观看状态。当前为限制状态':'限制时，教师与家长的观看时间段相同，不限制时教师为全天候都可观看状态。当前为不限制状态';
                    let liveDeviceRule=res.data.content.list[0].liveDeviceRule;
                    // 获取开放时间设置
                    // 把后台HH:mm转成HH:mm:ss
                    // 添加时间段时再截取成HH:mm
                    let startFirst=liveDeviceRule.openStartTimeFirst,
                        endFirst=liveDeviceRule.openEndTimeFirst,
                        startSecond=liveDeviceRule.openStartTimeSecond,
                        endSecond=liveDeviceRule.openEndTimeSecond,
                        startThird=liveDeviceRule.openStartTimeThird,
                        endThird=liveDeviceRule.openEndTimeThird,
                        fClassId=liveDeviceRule.fClassId,
                        pId=liveDeviceRule.pId;
                    this.openTimeList=[
                        {indexRow: '', beginTime: startFirst, endTime: endFirst, fClassId, pId},
                        {indexRow: '', beginTime: startSecond, endTime: endSecond, fClassId, pId},
                        {indexRow: '', beginTime: startThird, endTime: endThird, fClassId, pId}
                    ];
                }
            });
        },
       
          // 开放时间设置处  时间修改 按钮
        updateTime(row, index) {
            this.choseFillTime(index);
            if (this.choseFillTime(index)==true) {
                let currentDate=moment(new Date()).format('YYYY-MM-DD')+' ';// 当前年月日
                let startTime=row.beginTime===null?'':currentDate+row.beginTime;// (必须有年月日)
                let endTime=row.endTime===null?'':currentDate+row.endTime;
                this.addData.firstStart=this.openTimeList[0].beginTime===null?'':this.openTimeList[0].beginTime;// HH:mm:ss
                this.addData.firstEnd=this.openTimeList[0].endTime===null?'':this.openTimeList[0].endTime;
                this.addData.secondStart=this.openTimeList[1].beginTime===null?'':this.openTimeList[1].beginTime;
                this.addData.secondEnd=this.openTimeList[1].endTime===null?'':this.openTimeList[1].endTime;
                this.addData.thirdStart=this.openTimeList[2].beginTime===null?'':this.openTimeList[2].beginTime;
                this.addData.thirdEnd=this.openTimeList[2].endTime===null?'':this.openTimeList[2].endTime;
                this.addData.dialogAdd=true;
                this.addData.fClassId=this.formInline.schoolId;
                this.addData.pId=row.pId?row.pId:'';// 取rule里面的id，没有就给null
                this.addData.indexRow=index;
                this.addData.startTime=startTime;// 时间弹窗显示的时间
                this.addData.endTime=endTime;// 时间弹窗显示的时间
                this.updateRange(index);
            }
        },
        // 判断修改时间段，不能越级
        choseFillTime(index) {
            if (index==0) {
                return true
            } else if (index==1) {// 第二段 第一段不得为空
                if (this.openTimeList[0].beginTime) {
                    return true
                } else {
                    this.$message.info('请先设置时间段1！');
                    return false
                }
            } else if (index==2) {// 第二段 第二段不得为空
                if (this.openTimeList[1].beginTime) {
                    return true
                } else {
                    this.$message.info('请先设置时间段2！');
                    return false
                }
            }
            return true
        },
        updateRange(index) {
            switch (index) {
                case 0:// 点第一段
                    this.addData.startRange.start='00:00:00';
                    if (this.openTimeList[1].beginTime) {// 第二段存在
                        this.addData.startRange.end=this.addData.endRange.end=this.openTimeList[1].beginTime;
                    } else {
                        this.addData.startRange.end=this.addData.endRange.end='23:59:59';
                    }
                    break;
                case 1: // 点击第二段
                     // 有第一段
                    this.addData.startRange.start=this.openTimeList[0].endTime;// 开始时间从第一段的结束开始
                    if (this.openTimeList[2].beginTime) {// 如果第三段存在
                        this.addData.startRange.end=this.addData.endRange.end=this.openTimeList[2].beginTime;
                    } else {
                        this.addData.startRange.end=this.addData.endRange.end='23:59:59';
                    }
                    break;
                case 2:// 点击最后一段 一定有第二段
                    this.addData.startRange.start=this.openTimeList[1].endTime;
                    this.addData.startRange.end='23:59:59';
                    this.addData.endRange.end='23:59:59';
                    break;
                default:
                    break;
            }
        },
        // 设备详情：
        // 设备关闭或者开放
        deviceClose(row) {
            if (row.sOpen=='1') {
                let status='1';
                this.areaOpen(status, row);
            } if (row.sOpen=='0') {
                let status='0';
                this.areaOpen(status, row);
            }
        },
        // 关闭、收费、限制
        // 收费是1，不收费0
        closeChargeLimit(row) {
            if (row.btn=='关闭') {
                let status='1';
                let parent='parent'
                this.areaOpen(status, parent);
            } if (row.btn=='开放') {
                let status='0';
                let parent='parent'
                this.areaOpen(status, parent);
            }
            if (row.btn=='收费') {
                let status='0';
                this.change(status);
            }
            if (row.btn=='免费') {
                let status='1';
                this.change(status);
            } 
            if (row.btn=='限制') {
                let status='0';
                this.limit(status);
            } 
            if (row.btn=='不限制') {
                let status='1';
                this.limit(status);
            }
        },
         // 请求后的message提示
        messageMsg(res, successMes) {
            this.$message({
                type: 'success',
                message: successMes
            });
            this.searchFetchData();
        },
        // 开放不开放的功能
        areaOpen(status, childOrparent) {
            let successMes=status=='0'?'设置开放成功':'设置关闭成功';
            let confirmMes=status=='0'?'确认开放后，该摄像头将对所有家长开放，确认开放吗？':'确认关闭后，该摄像头将不对所有学生家长开放，确认关闭吗？';
            // 总关闭和开放 传下面的两个pid
            let pIds=null;
            // //console.log(childOrparent, 'childOrparent')
            if (childOrparent=='parent') {
                // //console.log('点击了总开关！')
                pIds=this.pIdArr
            } else {
                pIds=[childOrparent.pId]
            }
            let sOpen=status;
            this.$confirm(confirmMes, ' ', {
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            }).then(() => {
                updatePublicAreaOpen(pIds, sOpen).then(res => {
                    this.messageMsg(res, successMes)
                });
            }).catch(() => {
                this.$message.info('已取消操作')
            });
        },
          // 收费不收费的功能
        change(status) {
            let successMes=status=='0'?'设置收费成功':'设置免费成功';
            let confirmMes=status=='0'?'确认收费后，移动端在公共区域开放状态下可收费观看，确认收费吗？':'确认免费后，移动端在公共区域开放状态下可免费观看，确认免费吗？';
            let sClassId=this.formInline.schoolId;// 学校id
            let sCharge=status;
            this.$confirm(confirmMes, ' ', {
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            }).then(() => {
                updatePublicAreaCharge(sClassId, sCharge).then(res => {
                    this.messageMsg(res, successMes)
                });
            }).catch(() => {
                this.$message.info('已取消操作')
            });
        },
           // 限制不限制的功能
        limit(status) {
            let successMes=status=='0'?'设置限制成功':'设置不限制成功';
            let confirmMes=status=='0'?'设置后，老师观看的时间段将会与家长的观看时间段相同，确认设置吗？':'设置后，老师会变为全天候都可以观看状态，确认设置吗？';
            let sClassId=this.formInline.schoolId;// 学校id
            let classIds=[];
            let sFlag=status;
            this.$confirm(confirmMes, ' ', {
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            }).then(() => {
                updateDeviceFlag(sClassId, classIds, sFlag).then(res => {
                    this.messageMsg(res, successMes)
                });
            }).catch(() => {
                this.$message.info('已取消操作')
            });
        },
         // 分页
        handleSizeChange(val) {
            this.loading = true;
            this.listQuery.page = 1;
            this.ChangePageSize(val);
            this.searchFetchData();
        },
        handleCurrentChange(val) {
            this.loading = true;
            this.listQuery.page = val;
            this.searchFetchData();
        }
    }
}
</script>

<style lang="scss" scoped>
    .form-box{
        display: none;

    }
    .formInline {
        .formBtn {
            width: 100%;
            height: 70px;
            border-top: 1px solid #dddddd;
            position: relative;
            .btnPosition {
                position: absolute;
                right: 0px;
                top: 18px;
            }
        }
    }
    .table-title {
        display: flex;
        justify-content: space-between;
        padding: 20px;
        color: #333;
        font-size: 18px;
        background: #fff;
    }
 .table-region{
    margin: 20px 2px 2px; 
    box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.1);
   -webkit-box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.1);
   .pagination-container {
        text-align: right;
        padding: 20px 0;
        padding-right: 20px;
        background: #fff;
    }
}
   
</style>

